/**
 * 获取未读消息接口
 */

//引入Q模块
let Q = require('q');
//存放商户数据库的变量
let db;

let index = function(getData, postData, config, _redis, _db) {
	let deferred = Q.defer();
	db = _db;
	if(postData.userId && postData.orderId && postData.timestamp) {
		db.select('storeOrder', {
			orderId: postData.orderId
		}).then(function(orderData) {
			if(orderData.userId == postData.userId) {
				//订单用户不匹配
				deferred.reject('-0110');
			}
			else if(orderData.length > 0) {
				orderData = orderData[0];
				orderDoneHandler(orderData).then(function(data) {
					deferred.resolve(['broadcast', {
						storeId: postData.storeId,
						type: 'sys',
						event: 'orderDone',
						data: {
							orderId: postData.orderId,
							timestamp: postData.timestamp,
							returnData: data
						}
					}]);
				}, function(errCode) {
					deferred.reject(errCode);
				});
			}
			else {
				//确认订单时没有找到对应订单
				deferred.reject('-0112');
			}
		}, function() {
			//确认结单时查询对应订单数据失败
			deferred.reject('-0111');
		});
	}
	else {
		//结束订单接口参数不足
		deferred.reject('-0103');
	}
	return deferred.promise;
}

let orderDoneHandler = function(orderData) {
	let deferred = Q.defer();
	switch(orderData.payMode) {
		case 'wxPay': 
			if(!orderData.userPayed) {
				//确认结单时发现用户未完成支付操作
				deferred.reject('-0104');
			}
			else if(orderData.orderDone) {
				//确认结单时发现此订单已经结单
				deferred.reject('-0105');
			}
			else if(orderData.storeReceiveMoney) {
				//确认结单时发现商家已经收到订单的款项
				deferred.reject('-0106');
			}
			else {
				wxPayDone(orderData).then(function(data) {
					deferred.resolve(data);
				}, function(errCode) {
					deferred.reject(errCode);
				});
			}
		break;
		case 'cashPay':
			if(orderData.orderDone) {
				//确认结单时发现此订单已经结单
				deferred.reject('-0105');
			}
			else if(orderData.storeReceiveMoney) {
				//确认结单时发现商家已经收到订单的款项
				deferred.reject('-0106');
			}
			else {
				cashPayDone(orderData).then(function(data) {
					deferred.resolve(data);
				}, function(errCode) {
					deferred.reject(errCode);
				});
			}
		break;
		default:
			//确认结单时得到了一个错误的支付类型
			deferred.reject('-0109');
		break;
	}
	return deferred.promise;
}

let wxPayDone = function(orderData) {
	let deferred = Q.defer();
	db.update('storeOrder', {
		orderId: orderData.orderId
	}, {
		orderDone: true
	}).then(function() {
		deferred.resolve(1);
	}, function() {
		//确认结单时更新微信支付的订单的状态失败
		deferred.reject('-0107');
	});
	return deferred.promise;
}

let cashPayDone = function(orderData) {
	let deferred = Q.defer();
	db.update('storeOrder', {
		orderId: orderData.orderId
	}, {
		userPayed: true,
		storeReceiveMoney: true,
		orderDone: true
	}).then(function() {
		deferred.resolve(1);
	}, function() {
		//确认结单时更新现金支付的订单的状态失败
		deferred.reject('-0108');
	});
	return deferred.promise;
}

module.exports = {
	index: index
};